package com.baobao.action;


import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import com.baobao.dao.StudentDAO;
import com.baobao.domain.Address;
import com.baobao.domain.Parent;
import com.baobao.domain.Student;
import com.baobao.service.AddressService;
import com.baobao.service.ParentService;
import com.baobao.service.StudentService;

@Controller
@RequestMapping("/user")
public class UserAction {

	private static Logger log = LoggerFactory.getLogger(LeaveAction.class);
	
	@Autowired
	private StudentService studentService;
	
	@Autowired
	private ParentService parentService;
	
	@Autowired
	private AddressService addressService;
	/**
	 * 孩子列表
	 */
	@RequestMapping(value="/childs",  produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ResponseBody
	public String GetChild(HttpServletRequest request,
		@RequestParam(value="phone",required=true) String phone_num){
		
		System.out.println("Parent's phone is:" + phone_num);
		
		JSONArray childs = new JSONArray();
		JSONObject result = new JSONObject();
		//查找家长
		Parent parent = parentService.findParentByPrimaryKey(phone_num);
		
		if(parent == null)
		{
			result.put("error", "用户不存在");
			result.put("success", false);
		}
		else {
			result.put("success", true);
			//获取家长绑定的bbId
			if(parent.getBbId1() != null)
			{
				//根据bbId获取学生
				Set<Student> students = studentService.findStudentByBbId(parent.getBbId1());
				for (Student student : students) {
					childs.add(student);
				}					
			}
			if(parent.getBbId2() != null)
			{
				//根据bbId获取学生
				Set<Student> students = studentService.findStudentByBbId(parent.getBbId2());
				for (Student student : students) {
					childs.add(student);
				}	
			}
			if(parent.getBbId3() != null)
			{
				//根据bbId获取学生
				Set<Student> students = studentService.findStudentByBbId(parent.getBbId3());
				for (Student student : students) {
					childs.add(student);
				}	
			}
			if(parent.getBbId4() != null)
			{
				//根据bbId获取学生
				Set<Student> students = studentService.findStudentByBbId(parent.getBbId4());
				for (Student student : students) {
					childs.add(student);
				}	
			}
			if(parent.getBbId5() != null)
			{
				//根据bbId获取学生
				Set<Student> students = studentService.findStudentByBbId(parent.getBbId5());
				for (Student student : students) {
					childs.add(student);
				}	
			}
			try {
				result.put("message", childs);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}		
				
		System.out.println(childs.toString());		
		return result.toString();
	}
	
	/**
	 *用户登录
	 */
	@RequestMapping(value="/login",  produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ResponseBody
	public String ParentLogin(HttpServletRequest request,
		@RequestParam(value="phone",required=true) String phone,
		@RequestParam(value="password",required=true) String password){
		

		JSONObject result = new JSONObject();
		Parent parent = parentService.findParentByPrimaryKey(phone);
		
		if(parent == null)
		{
			result.put("error", "用户不存在");
			result.put("success", false);
		}
		else {
			if(parent.getPassword().equals(password) != true){
				result.put("error", "密码不正确");
				result.put("success", false);
			}
			else{
				result.put("success", true);
				result.put("message", JSONObject.fromObject(parent));
			}
		}
		
		return result.toString();
	}
	
	/**
	 *上传用户头像
	 */
	@RequestMapping(value="/uploadAvatar",  produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ResponseBody
	public String UploadAvatar(HttpServletRequest request,
		@RequestParam(value="phone",required=true) String phone,
		@RequestParam(value="image",required=true) String image){
		
		log.info("用户请求上传头像图片："+phone);
		JSONObject result = new JSONObject();
		Parent parent = parentService.findParentByPrimaryKey(phone);
		
		if(parent == null)
		{
			result.put("error", "用户尚未注册");
			result.put("success", false);
		}
		else {
			Set<Address> addressSet = addressService.findAddressByPhone(phone);
			
			if(addressSet.size() == 0)
			{
				result.put("error", "用户尚未绑定任何卡号");
				result.put("success", false);
			}
			else {
				for (Address address : addressSet) 
				{
					log.info("将用户头像数据写入数据库！大小为：" + image.length());
					address.setImgUrl(image);
					addressService.saveAddress(address);
					result.put("success", true);
				}				
			}
		}
		
		return result.toString();
	}
	
	/**
	 *用户注册
	 */
	@RequestMapping(value="/register",  produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ResponseBody
	public String ParentRegister(HttpServletRequest request,
		@RequestParam(value="phone",required=true) String phone,
		@RequestParam(value="authcode",required=true) String authcode,
		@RequestParam(value="password",required=true) String password){
		

		JSONObject result = new JSONObject();
		Parent parent = parentService.findParentByPrimaryKey(phone);
		
		if(parent != null)
		{
			result.put("error", "该手机号已经被注册");
			result.put("success", false);
		}
		else {
			if(authcode.equals("000000") != true){
				result.put("error", "手机验证码不正确");
				result.put("success", false);
			}
			else{
				Parent newParent = new Parent();
				newParent.setPhone(phone);
				newParent.setPassword(password);
				parentService.saveParent(newParent);
				result.put("success", true);
				result.put("message", JSONObject.fromObject(newParent));
			}
		}
		
		return result.toString();
	}
	
	private int _findBinded(Parent parent,String bbid){
		if(parent.getBbId1() != null && parent.getBbId1().equals(bbid) == true){
			return 1;			
		}
		else if(parent.getBbId2() != null && parent.getBbId2().equals(bbid) == true){
			return 2;			
		}
		else if(parent.getBbId3() != null && parent.getBbId3().equals(bbid) == true){
			return 3;			
		}
		else if(parent.getBbId4() != null && parent.getBbId4().equals(bbid) == true){
			return 4;			
		}
		else if(parent.getBbId5() != null && parent.getBbId5().equals(bbid) == true){
			return 5;			
		}
		return 0;
	}
	private boolean _findAndBindBbID(Parent parent,String bbid){
		
		
		if(parent.getBbId1() == null || parent.getBbId1().equals("") == true){
			parent.setBbId1(bbid);
			return true;
		}
		else if(parent.getBbId2()== null || parent.getBbId2().equals("") == true){
			parent.setBbId2(bbid);
			return true;
		}
		else if(parent.getBbId3()== null || parent.getBbId3().equals("") == true){
			parent.setBbId3(bbid);
			return true;
		}
		else if(parent.getBbId4()== null || parent.getBbId4().equals("") == true){
			parent.setBbId4(bbid);
			return true;
		}
		else if(parent.getBbId5()== null || parent.getBbId5().equals("") == true){
			parent.setBbId5(bbid);
			return true;
		}
		return false;
	}
	/**
	 *绑定卡号
	 */
	@RequestMapping(value="/bind",  produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ResponseBody
	public String ParentBind(HttpServletRequest request,
		@RequestParam(value="phone",required=true) String phone,
		@RequestParam(value="name",required=true) String name,
		@RequestParam(value="childname",required=true) String childname,
		@RequestParam(value="bbid",required=true) String bbid,
		@RequestParam(value="relation",required=true) int relation){
		

		JSONObject result = new JSONObject();
		Parent parent = parentService.findParentByPrimaryKey(phone);
		Set<Student> students = studentService.findStudentByBbId(bbid);
		if(parent == null)
		{
			result.put("error", "用户未注册，不能绑定卡号");
			result.put("success", false);
		}
		else {
			if(students.size() == 0){
				result.put("error", "BB卡号不存在");
				result.put("success", false);
			}
			else{
				Student student = null;
				for (Student studenttmp : students) {
					student = studenttmp;
				}
				if(student.getName().equals(childname) != true)
				{
					result.put("error", "孩子姓名与卡号不匹配");
					result.put("success", false);
				}
				else{
					if(_findBinded(parent, bbid) != 0)
					{
						result.put("error", "该卡号已经被绑定");
						result.put("success", false);
					}
					else {
						parent.setRelation(relation);
						if(_findAndBindBbID(parent, bbid)!=true)
						{
							result.put("error", "最多允许绑定5个卡号");
							result.put("success", false);
						}
						else{
							parent.setName(name);
							parentService.saveParent(parent);
							result.put("success", true);
							result.put("message", JSONObject.fromObject(parent));
							
							//更新家长通讯录表
							Address address = new Address();
							address.setPhone(phone);
							address.setBanjiId(student.getClassId());
							//address.setImgUrl("");
							addressService.saveAddress(address);
							log.info("增加家长通讯录。家长phone："+phone+"；所属班级："+student.getClassId());
						}	
					}									
				}
			}
		}
		
		
		
		
		return result.toString();
	}
}
